/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Login.java
 *
 * Created on 24/04/2011, 11:06:17 AM
 */
package vista;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.Arrays;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author XIOMARA BUITRAGO
 */
public class Login extends javax.swing.JFrame {

    /** Creates new form Login */
    public Login() {
        initComponents();
        inicializacion();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblUser = new javax.swing.JLabel();
        txtUser = new javax.swing.JTextField();
        lblPass = new javax.swing.JLabel();
        btnOK = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        lblInfo = new javax.swing.JLabel();
        txtPass = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login");

        lblUser.setText("Usuario: ");

        lblPass.setText("Contraseña:");

        btnOK.setText("Aceptar");
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancelar");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        lblInfo.setForeground(new java.awt.Color(153, 0, 0));

        txtPass.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPassActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblInfo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblUser, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblPass))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtPass, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
                            .addComponent(txtUser, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(btnOK)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblInfo, javax.swing.GroupLayout.DEFAULT_SIZE, 14, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblUser)
                    .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPass)
                    .addComponent(txtPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnOK)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
        // TODO add your handling code here:
        String user = txtUser.getText();
        char[] password = txtPass.getPassword();
        btnOK(user, password);
    }//GEN-LAST:event_btnOKActionPerformed

    private void txtPassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPassActionPerformed
        // TODO add your handling code here:
        String user = txtUser.getText();
        char[] password = txtPass.getPassword();
        btnOK(user, password);
    }//GEN-LAST:event_txtPassActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Login().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOK;
    private javax.swing.JLabel lblInfo;
    private javax.swing.JLabel lblPass;
    private javax.swing.JLabel lblUser;
    private javax.swing.JPasswordField txtPass;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables
    /**********************************************/
    /*************CODIGO PERSONAL******************/
    /**********************************************/
    private boolean isFirstTime;
    private char[] pass = {'j', 'x', 't', 'a', 's', 'e', 'c'};
    private final static String SECURITY_FOLDER_TAG = "seguridad";
    private final static String SECURITY_FILE_TAG = "login.keys";
    private final File securityFolder = new File(SECURITY_FOLDER_TAG);
    private final File keysFile = new File(securityFolder, SECURITY_FILE_TAG);
    private final static String charset = "UTF-8";
    private final static String digestAlgorithm = "SHA-1";

    /**
     * Método que es llamado por el constructor de esta clase.
     */
    private void inicializacion() {
        getRootPane().setDefaultButton(btnOK);
        if (keysFile.exists()) {
            isFirstTime = false;
        } else {
            try {
                isFirstTime = true;
                if (securityFolder.mkdir() && keysFile.createNewFile()) {
                    System.out.println("Creado archivo satisfactoriamente por primera vez");
                } else {
                    System.out.println("Error en la creación del archivo de contraseñas por primera vez");
                }
                lblInfo.setText("Ingrezando por primera vez.");
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "Error al crear el archivo " + SECURITY_FILE_TAG, "Error de Llaves", JOptionPane.ERROR_MESSAGE);
                Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Método que verifica que las credenciales proporcionadas por el usuario sean correctas.
     * @param user El usuario
     * @param password La contraseña
     */
    private void btnOK(String user, char[] password) {
        FileInputStream fis = null;
        if(user == null || password == null){
            setInfoMessage("No olvide ingresar sus credenciales");
            return;
        }

        try {
            Properties properties = new Properties();
            fis = new FileInputStream(keysFile);
            InputStreamReader isr = new InputStreamReader(fis, charset);
            BufferedReader br = new BufferedReader(isr);

            properties.load(br);
            if (isFirstTime) {
                MessageDigest sha = MessageDigest.getInstance(digestAlgorithm);
                String passString = new String(password);
                sha.update(passString.getBytes());
                byte[] digest = sha.digest();
                properties.setProperty(user, new String(digest));
                FileOutputStream fos = new FileOutputStream(keysFile);
                OutputStreamWriter osw = new OutputStreamWriter(fos, charset);
                PrintWriter pw = new PrintWriter(osw);
                properties.store(pw, "Archivo de claves de autenticación");
                setInfoMessage("La clave ha sido creada satisfactoriamente");
                isFirstTime = false;
            } else {
                String realPass = properties.getProperty(user);
                if(realPass == null){
                    setInfoMessage("El usuario no existe");
                    return;
                }

                System.out.println("User Pass: " + realPass);
                MessageDigest sha = MessageDigest.getInstance(digestAlgorithm);
                sha.update(new String(password).getBytes());
                String userPass = new String(sha.digest());
                if (realPass.equals(userPass)) {
                    //JOptionPane.showMessageDialog(this, "Acreditado Satisfactoriamente", "Información", JOptionPane.INFORMATION_MESSAGE);
                    javax.swing.SwingUtilities.invokeLater(new Runnable() {

                        public void run() {
                            new Inicio().setVisible(true);
                        }
                    });
                    this.dispose();
                } else {
                    JOptionPane.showMessageDialog(this, "Error de Autenticación", "Información", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void setInfoMessage(String message) {
        lblInfo.setText(message);
    }
}
